<template>
    <div class="app-container">
        <el-form ref="searchForm" inline :model="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="分类名称：" prop="name">
                        <el-input clearable v-model="searchForm.name" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="可用性：" prop="usingStatus">
                        <el-select clearable v-model="searchForm.usingStatus" placeholder="请选择">
                            <el-option v-for="item in usingStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button @click="init('search')" type="primary">查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick(1)" type="primary" style="position: absolute;right: 0;">添加顶级分类</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" style="width: 100%;margin: 20px 0px;" border row-key="id" id="treeTable">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="name" label="分类名称" width="180"></el-table-column>
            <el-table-column label="封面图" align="center">
                <template slot-scope="scope">
                    <!-- <img v-if="scope.row.coverUrl" :src="scope.row.showpic" width="50" height="50" alt="/图片" @click="enlargeFun(scope.row.showpic)"> -->
                    <img v-if="scope.row.coverUrl" :src="scope.row.coverUrl" width="50" height="50" alt="/图片" @click="enlargeFun(scope.row.coverUrl)">
                    <img v-else src="@/assets/image/default.png" width="50" height="50" alt="/图片">
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sort" label="顺序值" width="80" align="center"></el-table-column>
            <el-table-column prop="usingStatus" :formatter="usingStatusFun" label="可用性" width="80" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="260">
                <template slot-scope="scope">
                    <el-button style="margin-bottom: 5px;" @click.stop="editClick(scope.row)" type="primary" plain size="mini">编辑</el-button>
                    <el-button style="margin-bottom: 5px;" @click.stop="addClick(2,scope.row)" plain size="mini">添加子分类</el-button>
                    <el-button style="margin-bottom: 5px;" @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="封面图：" prop="coverUrl">
                    <el-upload class="avatar-uploader" action="" :http-request="UploadImage" :show-file-list="false" :before-upload="beforeAvatarUpload" >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" width="100%">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分类名称：" prop="name">
                    <el-input v-model="dataForm.name" placeholder="必填项。请输入分类名称"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="description">
                    <el-input v-model="dataForm.description" type="textarea" :rows="4" placeholder="必填项。请输入描述内容"></el-input>
                </el-form-item>
                <el-form-item label="顺序值：" prop="sort">
                    <el-input v-model="dataForm.sort" type="number" placeholder="请输入顺序值"></el-input>
                </el-form-item>
                <el-form-item label="可用性：" prop="usingStatus">
                    <el-select v-model="dataForm.usingStatus" placeholder="请选择可用性" style="width: 100%;">
                        <el-option v-for="item in usingStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 图片弹框 -->
        <el-dialog :visible.sync="showPicDialog" width="1000px">
            <img :src="nowPic" alt="" style="max-width: 100%;margin: 0 auto 15px;display: inherit" />
        </el-dialog>
    </div>
</template>
<script>
import { addCategory, findCategory, editCategory, detailCategory, delCategory } from '@/api/product/product-category'
import { uploadPic, getPic } from '@/api/uploadPic'
import { getCookie, setCookie } from '@/utils/auth'
export default {
    name: 'ProductCategory',
    data() {
        return{
            nowId: '',
            showDialog: false,
            dataForm: {
                coverUrl: '',
                name: '',
                description: '',
                sort: '',
                usingStatus: 1,
            },
            rules: {
                name: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
                description: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
            },
            searchForm: {
                parentId: [],
                name: '',
                usingStatus: '',
            },
            nowPage: 0,
            pageSize: 10,
            imageUrl: '',
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            showPicDialog: false,
            nowPic: '',
            parentOpt: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            tableData: [],
            usingStatusOpt: [
                {label: '启用', value: 1},
                {label: '禁用', value: 0}
            ],
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            // let cid = '';
            // if(this.searchForm.parentId.length != 0){
            //     cid = this.searchForm.parentId[this.searchForm.parentId.length - 1];
            // }
            _this.tableData = [];
            //获取列表信息
            findCategory(_this.nowPage, _this.pageSize,_this.searchForm.name,_this.searchForm.usingStatus).then(response => {
                if(response.code == 200){
                    if(response.object){
                        _this.pageData = response.object
                        _this.tableData = response.object.content
                        // if(response.object.content){
                        //     _this.$nextTick(()=>{
                        //         _this.tableData = _this.getTreeData(response.object.content);
                        //     })
                        // }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            const _this = this;
            for(var i=0;i<data.length;i++){
                let obj = data[i];
                if(data[i].coverUrl != ''){
                    getPic(data[i].coverUrl).then(res => {
                        if(res.code == 200){
                            _this.$set(obj,'showpic',res.object);
                            if((obj.children != null) &&  (obj.children.length>0)){
                                _this.getTreeData(obj.children);
                            }
                        }else{
                            _this.$message.error(res.message);
                        }
                    })
                }else{
                    _this.$set(data[i],'showpic','');
                }
            }
            return data;
        },
        //添加
        addClick(type,row){
            this.popStatus = 0;
            this.showDialog = true;
            //父级栏目id
            if(type == 1){
                this.dataForm.parentId = '0';
            }else if(type == 2){
                this.dataForm.parentId = row.id;
            }
            this.dataForm.name = '';
            this.dataForm.description = '';
            this.dataForm.sort = '';
            this.dataForm.coverUrl = '';
            this.dataForm.usingStatus = 1;
            this.imageUrl = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //提交添加
        addSubmit(formName){
            const _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(!_this.dataForm.parentId){  //设置默认值
                        _this.dataForm.parentId = '0';
                    }
                    //提交
                    if(_this.popStatus == 0){  //添加
                        addCategory(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })

                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editCategory(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.name+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delCategory(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.dataForm.name = row.name;
            this.dataForm.description = row.description;
            this.dataForm.sort = row.sort;
            this.dataForm.parentId = row.parentId;
            this.dataForm.coverUrl = row.coverUrl;
            this.dataForm.usingStatus = row.usingStatus;
            if(row.coverUrl){
                this.imageUrl = row.showpic;
            }else{
                this.imageUrl = '';
            }
            this.showDialog = true;
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.$refs[formName].resetFields();
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        usingStatusFun(row){
            if(row.usingStatus == 1){
                return '启用'
            }else if(row.usingStatus == 0){
                return '禁用'
            }
        },
        //自定义上传
        UploadImage(param){
            const _this = this;
            //上传图片
            let formData = new FormData();
            formData.append('photoFile', param.file);
            formData.append('dir', 'ProductCategory');
            formData.append('fileType', '1');
            uploadPic(formData).then(response => {
                if(response.code == 200){
                    _this.dataForm.coverUrl = response.object.saveImage;
                    this.imageUrl = response.object.showImage;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //准备上传
        beforeAvatarUpload(file){
            const isJPG = file.type;
            const isLt2M = file.size / 1024 / 1024 < 4;
            if(((isJPG === 'image/jpeg') || (isJPG === 'image/png') || (isJPG === 'image/jpg') || (isJPG === 'image/gif') || (isJPG === 'image/JPEG') || (isJPG === 'image/PNG') || (isJPG === 'image/JPG') || (isJPG === 'image/GIF')) == false){
                this.$message.error('上传图片只能是 jpeg、png、jpg、gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 4MB!');
            }
            return isJPG && isLt2M;
        },
        //放大图片
        enlargeFun(pic){
            this.showPicDialog = true;
            this.nowPic = pic;
        },
    },
    mounted(){
        this.init();
    }
}
</script>
<style>
    #treeTable .el-icon-arrow-right:before{
        color: #2196f3;
        font-weight: bold;
        /* content: "\E6DC"; */
        content: "\E791";
    }
    #treeTable .el-table__row,#treeTable .el-table__row.el-table__row--level-0{
        background: #e8f4ff;
    }
    #treeTable .el-table__row.el-table__row--level-1{
        background: #f0f9eb;
    }
    #treeTable .el-table__row.el-table__row--level-2{
        background: oldlace;
    }
    #treeTable tr.hover-row > td{
        background-color: initial;
    }
    #treeTable.el-table th > .cell{
        text-align: center;
    }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
